﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Roles;
using MediatR;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Roles
{
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, APIResult<int>>
    {
        IBaseRepository<Role> rRep;
        ILogger<AddRoleCommandHandler> logger;
        public AddRoleCommandHandler(IBaseRepository<Role> rRep, ILogger<AddRoleCommandHandler> logger)
        {
            this.rRep = rRep;
            this.logger = logger;
        }
        public async Task<APIResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 检查角色名称是否已存在
                var existingRole = await rRep.GetAsync(r => r.RoleName == request.RoleName);
                if (existingRole != null)
                {
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "角色名称已存在",
                        Data = 0
                    };
                }
                // 创建新角色
                var newRole = new Role
                {
                    RoleName = request.RoleName,
                    DeptDesc = request.DeptDesc ?? string.Empty,
                    RoleStatus = 1, // 默认状态为启用
                    RoleMemberNumber = 100, // 初始成员数量为0
                    UpdTime = DateTime.Now // 设置更新时间
                };
                // 添加角色到数据库
                var result = await rRep.AddAsync(newRole);
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "添加角色成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加角色失败");
                throw;
            }
        }
    }
}
